//
//  WDCollectionView.swift
//  UIKitExtentions
//
//  Created by Alean on 2023/5/11.
//

import Foundation

open class CollectionDataSource: NSObject, UICollectionViewDataSource, UICollectionViewDelegate {
    fileprivate weak var collectionView: UICollectionView?

    internal final var flowLayout: (() -> UICollectionViewFlowLayout)?
    @discardableResult
    public final func flowLayout(_ handler: @escaping (() -> UICollectionViewFlowLayout)) -> Self {
        flowLayout = handler
        if let flowLayout = flowLayout {
            self.collectionView?.collectionViewLayout = flowLayout()
        }
        return self
    }

    internal final var onScroll: ((UIScrollView) -> Void)?
    @discardableResult
    public final func onScroll(_ handler: @escaping ((UIScrollView) -> Void)) -> Self {
        onScroll = handler
        return self
    }

    internal final var onCellSelected: ((UICollectionView, IndexPath) -> Void)?
    @discardableResult
    public final func onCellSelected(_ handler: @escaping ((UICollectionView, IndexPath) -> Void)) -> Self {
        onCellSelected = handler
        return self
    }

    internal final var numberOfSections: ((UICollectionView) -> Int)?
    @discardableResult
    public final func numberOfSections(_ handler: @escaping ((UICollectionView) -> Int)) -> Self {
        numberOfSections = handler
        return self
    }

    internal final var items: ((UICollectionView, IndexPath) -> [ObjectRenderable]?)?
    @discardableResult
    public final func items(_ handler: @escaping ((UICollectionView, IndexPath) -> [ObjectRenderable]?)) -> Self {
        items = handler
        return self
    }

    internal final var cellForRow: ((UICollectionView, IndexPath, ObjectRenderable?) -> (UICollectionViewCell?))?
    @discardableResult
    public final func cellForRow(_ handler: @escaping ((UICollectionView, IndexPath, ObjectRenderable?) -> (UICollectionViewCell?))) -> Self {
        cellForRow = handler
        return self
    }

    @discardableResult
    public func cellRegister(_ cellTypes: [UICollectionViewCell.Type]) -> Self {
        for cellType in cellTypes {
            collectionView?.register(cellType)
//            tableView?.register(cellType, forCellReuseIdentifier: cellType.identifier)
        }
        return self
    }

    deinit {
        collectionView?.delegate = nil
        collectionView?.dataSource = nil
        NotificationCenter.default.removeObserver(self)
    }

    @discardableResult
    public func reload() -> Self {
//        collectionView?.reloadData()
        DispatchMain {
            self.collectionView?.performBatchUpdates {
            } completion: { (_) in
                self.collectionView?.reloadData()
            }
        }

        return self
    }

//    public init<T: TableRenderable>(tableView: UITableView, cellTypes: [T.Type]) {
    public init(collectionView: UICollectionView) {
        super.init()
        self.collectionView = collectionView
        collectionView.delegate = self
        collectionView.dataSource = self
    }

    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        onScroll?(scrollView)
    }

    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        if let numberOfSections = numberOfSections {
            return numberOfSections(collectionView)
        }
        return 1
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items?(collectionView, IndexPath(row: 0, section: section))?.count ?? 0
    }

    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: WDSearchShopCell.identifier, for: indexPath) as! WDSearchShopCell
//        cell.data = self.viewModel?.list?[indexPath.row]
        if let items = items, let datas = items(collectionView, indexPath), !datas.isEmpty {
            if let cellForRow = cellForRow,
               let cell = cellForRow(collectionView, indexPath, datas[safe: indexPath.row])
            {
                return cell
            }
        }
        return UICollectionViewCell()
    }

    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        onCellSelected?(collectionView, indexPath)
    }
}

extension CollectionDataSource: UICollectionViewDelegateFlowLayout {
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.zero//UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)
    }
}
class CCell: WDBaseCollectionCell<Model> {
    
}
open class WDCollectionView: WDBaseFormView<UICollectionView> {
    private lazy var defaultFlowLayout: UICollectionViewFlowLayout = {
        let flowLayout = UICollectionViewFlowLayout()
//        flowLayout.scrollDirection = .vertical
//        flowLayout.minimumInteritemSpacing = 0
//        flowLayout.minimumLineSpacing = 0
//        flowLayout.itemSize = CGSizeMake(60, 80)
        return flowLayout
    }()

    private lazy var collectionView: UICollectionView = {
        let mainView = UICollectionView(frame: self.bounds, collectionViewLayout: defaultFlowLayout)
        mainView.backgroundColor = UIColor.clear
        mainView.isPagingEnabled = false
        mainView.scrollsToTop = false
        mainView.showsHorizontalScrollIndicator = false
        mainView.showsVerticalScrollIndicator = false
        if #available(iOS 11.0, *) {
            mainView.contentInsetAdjustmentBehavior = .never
        } else {
            topViewController()?.automaticallyAdjustsScrollViewInsets = false
        }
//        mainView.contentInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)

//        mainView.register(WDTypeSelectCell.self, forCellWithReuseIdentifier: WDTypeSelectCell.identifier)
//        mainView.dataSource = self
//        mainView.delegate = self
        return mainView
    }()

    public lazy var dataSource: CollectionDataSource = CollectionDataSource(collectionView: collectionView)

    public override func initContent() {
        super.initContent()
        formContentView(view: collectionView)
        
//        dataSource.flowLayout {
//            let flowLayout = UICollectionViewFlowLayout()
//            flowLayout.scrollDirection = .vertical
//            flowLayout.minimumInteritemSpacing = 0
//            flowLayout.minimumLineSpacing = 0
//            return flowLayout
//        }.onCellSelected { collectionView, indexPath in
//            print("item = \(indexPath.item)")
//        }.items { collectionView, indexPath in
//            return [WDBaseModel(), WDBaseModel()]
//        }.cellRegister([CCell.self])
    }
}
